package com.smedi.ismedi.notification.core.infrastructure.schedule;

import com.smedi.ismedi.cache.starter.util.SafetyLockUtil;
import com.smedi.ismedi.notification.core.domain.aggregatemodel.SmsTemplate;
import com.smedi.ismedi.notification.core.domain.service.SmsTemplateDomainService;
import com.smedi.ismedi.notification.core.infrastructure.constant.ConstantField;
import com.smedi.ismedi.notification.core.infrastructure.enumerate.SmsTemplateStatusEnum;
import com.smedi.ismedi.notification.core.port.service.SmsClientRemoteApiService;
import com.tencentcloudapi.sms.v20190711.models.DescribeSmsTemplateListResponse;
import com.tencentcloudapi.sms.v20190711.models.DescribeTemplateListStatus;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@Slf4j
@Component
@RequiredArgsConstructor
public class RefreshSmsTemplateStatusSchedule {
    private final SafetyLockUtil safetyLockUtil;

    @Value("${spring.application.name}")
    private String application;

    private final SmsTemplateDomainService smsTemplateDomainService;

    private final SmsClientRemoteApiService smsClientRemoteApiService;

    /**
     * 每隔1小时执行一次刷新动作
     */
    @Scheduled(cron = "0 0 0/1 * * ? ")
    public void scheduleTask() {
        String lockKey = ConstantField.doSyncTask(application);
        log.info(">>> 开始同步短信模板状态。");

        // 执行加锁代码
        safetyLockUtil.calc(() -> {
            List<SmsTemplate> inApprovals = smsTemplateDomainService.findListBySmsTemplateStatus(SmsTemplateStatusEnum.IN_APPROVAL.getValue());
            List<Long> tencentTemplateIds = inApprovals.stream().map(smsTemplate -> smsTemplate.getTencentTemplateId()).collect(Collectors.toList());

            try {
                DescribeSmsTemplateListResponse response = smsClientRemoteApiService.getSmsTemplateStatus(tencentTemplateIds);
                for (DescribeTemplateListStatus status : response.getDescribeTemplateStatusSet()) {
                    Optional<SmsTemplate> optional = inApprovals.stream().filter(smsTemplate -> status.getTemplateId().equals(smsTemplate.getTencentTemplateId())).findFirst();
                    if (optional.isPresent()) {
                        smsTemplateDomainService.updateTemplateStatus(optional.get().getTencentTemplateId(), status.getStatusCode());
                    }
                }
            } catch (Exception e) {
                log.error("同步短信模板状态失败，错误：{}", e);
            }
        }, lockKey, 5, 120, 0, 1, false);

        log.info("短信模板状态同步结束");
    }
}
